package com.payment.common.utils.aliyun;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CannedAccessControlList;
import com.payment.common.enums.ProjectName;
import com.payment.common.utils.PropertiesUtil;
import com.payment.common.utils.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.Random;

/**
 * @author fuzhili
 * @Description:
 * @date 2019/4/25 9:12
 */
public class OSSClientUtil {

    private static String endpoint = PropertiesUtil.getProperty("endpoint");
    private static String accessKeyId = PropertiesUtil.getProperty("accessKeyId");
    private static String accessKeySecret = PropertiesUtil.getProperty("accessKeySecret");
    private static String bucketName = ProjectName.SMALL_CATTLE.getCode();

    private static OSSClient ossClient;

    public OSSClientUtil() {
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }

    /**
     * 初始化
     */
    public void init() {
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }

    /**
     * 销毁
     */
    public void destory() {
        ossClient.shutdown();
    }


    public static String uploadImg2Oss(MultipartFile file, String filedir) throws Exception {
        if (file.getSize() > (1024 * 1024 * 5)) {
            throw new Exception("上传图片大小不能超过5M！");
        }
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);

        if (suffix.equalsIgnoreCase("jpeg") || suffix.equalsIgnoreCase("jpg") || suffix.equalsIgnoreCase("png")) {

        } else {
            originalFilename = file.getOriginalFilename() + ".jpg";
        }

        Random random = new Random();
        String name = random.nextInt(10000) + System.currentTimeMillis() + originalFilename;
        try {
            InputStream inputStream = file.getInputStream();
            // 创建OSSClient实例。
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

            //设置bucket的访问权限， public-read-write权限
            ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            // 上传文件流。
            ossClient.putObject(bucketName, filedir + name, inputStream);
            ossClient.shutdown();
            inputStream.close();
            return getImgUrl(filedir + name);
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("图片上传失败");
        }
    }

    /**
     * 获得图片路径
     *
     * @param fileUrl
     * @return
     */
    public static String getImgUrl(String fileUrl) {
        // 创建OSSClient实例。
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        // 设置URL过期时间为1小时。
        Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000 * 365 * 10);
        // 生成以GET方法访问的签名URL，访客可以直接通过浏览器访问相关内容。
        URL url = ossClient.generatePresignedUrl(bucketName, fileUrl, expiration);
        // 关闭OSSClient。
        ossClient.shutdown();

        String fileUrlNow = url.toString();
        if (StringUtils.isNotEmpty(fileUrlNow) && fileUrlNow.contains("?")) {
            String[] r = fileUrlNow.split("[?]");
            fileUrlNow = r[0];
        }
        return fileUrlNow;
    }


    /**
     * Description: 判断OSS服务文件上传时文件的contentType
     *
     * @param FilenameExtension 文件后缀
     * @return String
     */
    public static String getcontentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
                FilenameExtension.equalsIgnoreCase(".jpg") ||
                FilenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpeg";
        }
        if (FilenameExtension.equalsIgnoreCase(".html")) {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase(".txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase(".vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase(".pptx") ||
                FilenameExtension.equalsIgnoreCase(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase(".docx") ||
                FilenameExtension.equalsIgnoreCase(".doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase(".xml")) {
            return "text/xml";
        }
        return "image/jpeg";
    }

}
